<template>
  <div class="search-suggestion">
    <van-cell
    v-for="(item, index) in suggestions"
    :key="index"
    icon="search"
    @click="$emit('search',item)"
    >
    <div slot="title" v-html="highlight(item)"></div>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestion } from '@/api/search.js'
export default {
  name: 'SearchSuggestion',
  components: {},
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      suggestions: [],
      timer: '',
      text: '',
      htmlStr: 'Hello <span style="color: red">World</span>'
    }
  },
  computed: {},
  watch: {
    searchText: {
      handler (value) {
        clearTimeout(this.timer)
        this.timer = setTimeout(() => {
          this.loadSearchSuggestion(value)
        }, 200)
      },
      immediate: true
    }
  },
  created () {},
  mounted () {},
  methods: {
    async loadSearchSuggestion (q) {
      try {
        const { data } = await getSearchSuggestion(q)
        this.suggestions = data.data.options
      } catch (err) {
        this.$toast('获取数据失败,请稍后重试')
      }
    },

    highlight (item) {
      const highlightStr = `<span class="active">${this.searchText}</span>`
      const reg = new RegExp(this.searchText, 'gi')
      return item.replace(reg, highlightStr)
    }
  }
}
</script>

<style scoped lang="less">
.search-suggestion {
 /deep/ span.active {
    color: red;
  }
}
</style>
